<template>
  <div id="content" v-loading="load">
    <!-- 顶部搜索区域 -->
    <div class="search">
      <div class="head-search" @click="toserachMsgs">
        <div>
          <i class="el-icon-search" style="margin-right: 6px"></i
          ><span>请输入要查询的关键字</span>
        </div>
      </div>
      <!-- 个人信息 -->
      <div class="userinfo">
        <div class="userinfo_left">
          <el-button
            type="success"
            round
            icon="el-icon-edit"
            size="mini"
            @click="addMsg"
            >发帖</el-button
          >
        </div>
        <div class="userinfo_right">
          <!-- <el-tag type="primary" size="mini">{{ permisstionStr }}</el-tag> -->
          <div @click="myInfo(userInfo.uid)" class="image">
            <el-avatar size="medium" :src="avatar_url"></el-avatar>
          </div>
          <span v-if="userInfo.nickname" @click="myInfo(userInfo.uid)">{{
            userInfo.nickname
          }}</span>
          <el-button
            type="danger"
            round
            icon="el-icon-user-solid"
            size="mini"
            style="margin-left: 5px; margin-right: 14px"
            @click="quit"
            v-if="userInfo.nickname"
            >登出</el-button
          >
          <el-button
            type="primary"
            v-else
            size="mini"
            icon="el-icon-user"
            style="margin-left: 5px; margin-right: 14px"
            round
            @click="toLogin"
          >
            登录
          </el-button>
        </div>
      </div>
      <!-- 新消息 -->
      <div class="message">
        <el-badge :value="mySubNum" class="item">
          <el-button
            round
            size="small"
            icon="el-icon-s-promotion"
            @click="getSub"
            >新动态</el-button
          >
        </el-badge>
        <el-badge :value="sysMessage" class="item">
          <el-button round size="small" @click="toSession">消息</el-button>
        </el-badge>
        <el-badge class="item">
          <el-button
            round
            style="margin-left: 84px"
            type="primary"
            size="small"
            icon="el-icon-search"
            @click="toSearchUser"
            >查找用户</el-button
          >
        </el-badge>
      </div>
      <!-- 帖子 -->
      <div
        class="detail-content"
        v-for="(message, index) in contentList"
        :key="message.mid"
      >
        <div class="detail">
          <div class="header">
            <div
              class="header-left"
              @click="getOtherUser(message.nickname, message.uid)"
            >
              <div class="avatar">
                <el-avatar size="medium" :src="message.avatar"></el-avatar>
              </div>
              <div class="username_time">
                <div class="username">{{ message.nickname }}</div>
                <div class="time">
                  <i class="el-icon-pie-chart"></i>{{ message.date }}
                </div>
              </div>
            </div>
            <div class="header-right">
              <el-button
                type="danger"
                size="mini"
                @click="deleteMsg(message, index)"
                v-if="userInfo.uid == message.uid"
                >删帖</el-button
              >
            </div>
          </div>
          <div class="message-content" @click="toMessageDetail(message)">
            <h4>{{ message.title }}</h4>
            <p>{{ message.content }}</p>
            <div class="message-imgs" v-if="message.images.length != 0">
              <div class="imgsbox" v-if="message.images.length == 1">
                <img
                  :src="message.images[0]"
                  style="
                    max-width: 355px;
                    max-height: 305px;
                    object-fit: cover;
                    border-radius: 5px;
                  "
                />
              </div>

              <div
                class="imgsbox"
                v-if="message.images.length >= 2 && message.images.length <= 4"
              >
                <el-image
                  v-for="(imgs, index) in message.images"
                  :key="index"
                  :src="imgs"
                  style="width: 45%; margin-right: 5px; display: inline-block"
                ></el-image>
              </div>

              <div class="imgsbox" v-if="message.images.length > 4">
                <el-image
                  v-for="(imgs, index) in message.images"
                  :key="index"
                  :src="imgs"
                  style="width: 30%; height: 80px; display: inline-block"
                ></el-image>
              </div>
            </div>
          </div>
          <div class="footer">
            <div class="watched">
              <i class="el-icon-view" size="mini"></i>
              <span>浏览:{{ message.views }}</span>
            </div>
            <div class="comments" @click="toMessageDetail(message)">
              <i class="el-icon-chat-line-square" size="mini"></i>
              <span>评论:{{ message.comments }}</span>
            </div>
            <div class="support" @click="kudos(message.mid, index)">
              <i
                v-if="message.mark == 1"
                class="el-icon-thumb"
                style="color: #007acc; font-weight: 700; font-size: 15px"
                size="medium"
              ></i>
              <i v-else class="el-icon-thumb" size="medium"></i>
              <span>点赞:{{ message.likes }} </span>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { mapState, mapGetters } from "vuex";
export default {
  name: "wswHome",

  data() {
    return {
      searchForm: {
        keyword: "",
      },
      contentList: [],

      load: false,
      sysMessage: null,
      mySubNum: null,
      page: 1,
      size: 8,
      isSeach: false,
      total: 10,
    };
  },
  computed: {
    ...mapState({
      userInfo: (state) => state.userInfo.userInfo,
      // permisstionStr(state) {
      //   const permissions = state.userInfo.userInfo.permission;
      //   if (permissions == 5) {
      //     return "普通用户";
      //   } else if (permissions == -9) {
      //     return "未登录";
      //   } else if (permissions == -1) {
      //     return "封禁用户";
      //   } else if (permissions == 7) {
      //     return "管理员";
      //   } else if (permissions == 8) {
      //     return "超级管理员";
      //   } else if (permissions == 9) {
      //     return "开发者";
      //   } else {
      //     return "未知用户";
      //   }
      // },

      // avatar_url: (state) => {
      //   if (state.userInfo.userInfo.avatar) {
      //     return "http://cdn.gdxywsw.club/" + state.userInfo.userInfo.avatar;
      //   } else {
      //     return "http://cdn.gdxywsw.club/2022-07-31 09:31:29徐浩东.png";
      //   }
      // },
      // message_avatar() {
      //   return this.contentList.map((item) => {
      //     item.avatar = "http://cdn.gdxywsw.club/" + item.avatar;
      //   });
      // },
    }),
    ...mapGetters(["avatar_url"]),
  },
  methods: {
    // 查看个人信息
    myInfo(uid) {
      if (uid) {
        this.$router.push({ name: "myInfo", params: { uid } });
      } else {
        this.$message({
          message: "请先登录",
          type: "info",
        });
      }
    },

    toserachMsgs() {
      this.$router.push("/searchMsg");
    },

    // 刷新
    flushed() {
      this.$router.go(0);
    },
    // 查看发帖人信息
    getOtherUser(username, uid) {
      if (this.userInfo.nickname) {
        this.$router.push({ name: "myInfo", params: { uid } });
      } else {
        this.$message({
          message: "请先登录",
          type: "info",
        });
      }
    },

    // 退出登录
    quit() {
      localStorage.removeItem("automatic-login");
      this.$store.dispatch("removeuserinfo");
      this.$router.push("/login");
      // let result = await this.$API.reqLoginOut();
      // if (result.code == 2000) {
      //   this.$router.push("/login");
      // } else {
      //   return Promise.reject(new Error(result.msg || "fail"));
      // }
    },
    // 跳转登录页
    toLogin() {
      localStorage.setItem("automatic-login", JSON.stringify(false));

      this.$router.push("/login");
    },
    // 搜索帖子
    async search() {
      this.load = true;
      let read = [];
      this.contentList.forEach((x) => {
        read.push(x.mid);
      });

      let result = await this.$API.reqSearch(
        this.userInfo.uid,
        null,
        null,
        null,
        read
      );

      if (result.code == 2000) {
        this.load = false;
        if (result.data.length == 0) {
          this.$message({
            message: "没有更多数据了哦",
            type: "info",
          });
          return;
        }
        this.contentList = [
          ...this.contentList,
          ...result.data.map((item) => {
            item.avatar = "http://cdn.gdxywsw.club/" + item.avatar;
            let newImages = [];
            for (let i of item.images) {
              i = "http://cdn.gdxywsw.club/" + i;
              newImages.push(i);
            }
            item.images = newImages;
            this.load = false;
            return item;
          }),
        ];
      } else {
        this.load = false;
        return Promise.reject(new Error("fail"));
      }
      this.load = false;
    },

    // 分页查看帖子
    // async getMsgByPage(page = 1,size,param) {
    //   let result = await this.$API.reqGetMessageByPage(page,size,param);
    //   if (result.code == 2000) {
    //     this.contentList = result.data.map((item) => {
    //       item.avatar = "http://cdn.gdxywsw.club/" + item.avatar;
    //       let newImages = [];
    //       for (let i of item.images) {
    //         i = "http://cdn.gdxywsw.club/" + i;
    //         newImages.push(i);
    //       }
    //       item.images = newImages;
    //       return item;
    //     });
    //   } else {
    //     return Promise.reject(new Error("fail"));
    //   }
    // },

    // 得到消息数量
    async getMessage() {
      let result = await this.$API.reqGetMessage();
      if (result.flag) {
        if (result.data === 0) {
          this.mySubNum = null;
        } else {
          this.mySubNum = result.data;
        }
      } else {
        return Promise.reject(new Error("fail"));
      }
    },

    // 得到未读消息数量
    async getUnReadMsg() {
      let result = await this.$API.reqGetUnReadMsg();
      if (result.flag) {
        if (result.data === 0) {
          this.sysMessage = null;
        } else {
          this.sysMessage = result.data;
        }
      } else {
        return Promise.reject(new Error("fail"));
      }
    },

    // 跳转查询用户页
    toSearchUser() {
      this.$router.push("/searchUser");
    },

    //清除未读
    /**
    clearUnRead() {
      this.sysMessage = null;
      this.mySubNum = null;
    },
     */

    //查看关注人的动态
    getSub() {
      this.$message({
        message: "该功能开发中",
        type: "info",
      });
      // if (!this.userInfo.username) {
      //   this.$message({
      //     message: "请先登录",
      //     type: "info",
      //   });
      // } else {
      //   this.$router.push("/mySub");
      //   this.mySubNum = null;
      // }
    },

    // 查看系统消息
    toSession() {
      this.$message({
        message: "该功能开发中",
        type: "info",
      });
      // if (!this.userInfo.username) {
      //   this.$message({
      //     message: "请先登录",
      //     type: "info",
      //   });
      // } else {
      //   this.sysMessage = null;
      //   this.$router.push("/sysSession");
      // }
    },

    // 查看帖子详情
    toMessageDetail(message) {
      // const { userInfo } = this.userInfo;
      let userInfo = this.userInfo;

      this.$router.push({ name: "delMsg", params: { message, userInfo } });
    },

    // 点赞
    async kudos(mid, i) {
      if (this.contentList[i].mark == 0) {
        this.contentList = this.contentList.map((item, index) => {
          if (index == i) {
            item.mark = 1;
            item.likes += 1;
          }
          return item;
        });
        let result = await this.$API.reqKudos(mid);
        if (result.code === 2000) {
          console.log("11");
        }
      } else {
        this.contentList = this.contentList.map((item, index) => {
          if (index == i) {
            item.mark = 0;
            item.likes -= 1;
          }
          return item;
        });
        let result = await this.$API.reqCancelKudos(mid);
        if (result.code === 2000) {
          console.log("22");
        }
      }
    },

    // 删帖
    async deleteMsg(message, index) {
      let result = await this.$API.reqDeleteMessage(message.mid);
      if (result.code == 2000) {
        this.contentList.splice(index, 1);
      }
    },

    // 发帖
    addMsg() {
      this.$router.push("/addMsg");
    },

    // 自动登录
    async autoLogin() {
      let result = await this.$API.reqAutoLogin();
      if (result.code == 2000) {
        this.$store.dispatch("setuserinfo", result.data);
      }
    },

    //上划加载
    handleScroll() {
      //变量scrollTop是滚动条滚动时，距离顶部的距离
      let scrollTop =
        document.documentElement.scrollTop || document.body.scrollTop;
      //变量windowHeight是可视区的高度
      let windowHeight =
        document.documentElement.clientHeight || document.body.clientHeight;
      //变量scrollHeight是滚动条的总高度
      let scrollHeight =
        document.documentElement.scrollHeight || document.body.scrollHeight;
      if (scrollTop + windowHeight >= scrollHeight - 15) {
        console.log("触底");
        if (this.load) {
          return;
        }

        this.page = this.page + 1;
        this.search(this.page);
      }
    },
  },

  mounted() {
    if (this.contentList.length == 0) {
      console.log("+++++");
      this.search();
    }

    if (JSON.parse(localStorage.getItem("automatic-login"))) {
      this.autoLogin();
    }

    window.addEventListener("scroll", this.handleScroll, false);
  },
  beforeDestroy() {
    window.removeEventListener("scroll", this.handleScroll);
  },
  destroyed() {
    console.log("1111");
    window.removeEventListener("scroll", this.handleScroll);
  },
};
</script>

<style lang="less" scoped>
.head-search {
  width: 93%;
  height: 25px;
  border-radius: 15px;
  border: 1px solid #e3e4e5;
  margin-bottom: 9px;
  line-height: 25px;
  padding-left: 7px;
  font-size: 12px;
  color: #989898;
}
.userinfo {
  display: flex;
  justify-content: space-between;

  .userinfo_right {
    display: flex;
    // justify-content: space-around;
    align-items: center;
    .el-tag {
      border: 0;
      margin-right: 8px;
    }
    .image {
      display: inline-block;
      width: 35px;
      height: 35px;
      margin-top: -6px;
      margin-right: 8px;
    }
  }
}
.message {
  margin-top: 15px;
  .item {
    margin-right: 15px;
  }
  .item:first-of-type {
    margin-right: 10px;
  }
}
.detail-content {
  margin-top: 10px;
  .detail {
    border: 1px solid #0078d4;
    margin-bottom: 5px;
    // .message-imgs {
    //   display: flex;
    //   justify-content: space-around;
    //   flex-wrap: wrap;
    //   .el-image {
    //     flex: 1;
    //   }
    // }
    .footer {
      display: flex;
      justify-content: space-around;
      align-items: center;
      font-size: 12px;
      font-weight: 400;
      div {
        margin: 3px 0;
        i {
          margin-right: 2px;
        }
      }
    }

    .header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      height: 50px;
      margin-top: 5px;
      .header-left {
        .avatar {
          margin: 3px;
        }
        display: flex;
        align-items: center;
        .username_time {
          .time {
            font-size: 12px;
          }
        }
      }
      .header-right {
        margin-top: -3px;
        margin-right: 5px;
      }
    }
    .message-content {
      .message-imgs {
        padding: 3px;
      }
      h4 {
        margin: 5px;
        padding: 0;
      }
      p {
        margin: 5px;
        font-size: 14px;
      }
      .el-image {
        margin: 5px;
      }
    }
  }
}
</style>